package cn.jinjimi.base.util;

import android.content.Context;
import android.text.TextUtils;
import android.util.Patterns;
import android.widget.EditText;

import cn.jinjimi.base.R;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Wilson on 14-8-21.
 */
public class StringUtils {
    private static final String TAG = StringUtils.class.getName();

    public static final String VERSION_SEPERATOR = ".";

//    private final static Pattern mobiler = Pattern.compile("^(13|14|15|17|18)\\d{9}$");
    private final static Pattern mobiler = Pattern.compile("\\d{11}$");

    private final static Pattern IDcarder = Pattern.compile("^(\\d{18,18}|\\d{17,17}(x|X))$");
//    private final static Pattern IDcarder = Pattern.compile("^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}([0-9]|X)$");

    private final static Pattern chineseName = Pattern.compile("^[a-zA-Z\\u4e00-\\u9fa5]{2,16}$");

    private final static Pattern password = Pattern.compile("^[a-zA-Z0-9~!@#$%^&*()_+-=`;:',.<>/\\\\|?\"\\{}\\]\\[]{6,20}$");

    private final static Pattern passporter = Pattern.compile("^1[45][0-9]{7}|G[0-9]{8}|P[0-9]{7}|S[0-9]{7,8}|D[0-9]+$");

    public static String IdCardFilter(String str) {
        str.replaceAll(" ", "");
        String regEx = "[^0-9xX]";
        Matcher m = Pattern.compile(regEx).matcher(str);
        return m.replaceAll("").trim();
    }

    public static String passPortFilter(String str) {
        str.replaceAll(" ", "");
        String regEx = "[^a-zA-Z0-9]";
        Matcher m = Pattern.compile(regEx).matcher(str);
        return m.replaceAll("").trim();
    }

    /**
     * 判断字符串是否为空
     *
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        if (str == null) return true;
        return TextUtils.isEmpty(str) || TextUtils.isEmpty(str.trim());
    }

    /**
     * 判断字符串是否不为空
     *
     * @param str
     * @return
     */
    public static boolean isNotEmpty(String str) {
        return !isEmpty(str);
    }

    /**
     * 判断是不是一个合法的电子邮件地址
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        if (email == null || email.trim().length() == 0)
            return false;
        return Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    /**
     * 判断是不是一个合法的手机号码
     *
     * @param mobile
     * @return
     */
    public static boolean isMobile(String mobile) {
        if (mobile == null || mobile.trim().length() == 0)
            return false;
        return mobiler.matcher(mobile).matches();
    }

    /**
     * 判断是不是一个合法的身份证号码
     *
     * @param idCard
     * @return
     */
    public static boolean isIDcard(String idCard) {
        if (isEmpty(idCard))
            return false;

        return IDcarder.matcher(idCard).matches();
    }

    /**
     * 判断是不是一个合法的证件号
     *
     * @param passport
     * @return
     */
    public static boolean isPassport(String passport) {
        if (isEmpty(passport))
            return false;
        return passporter.matcher(passport).matches();
    }

    public static boolean equalsString(String src, String target) {
        if (isEmpty(src) || isEmpty(target))
            return false;
        return src.equals(target);
    }

    /**
     * 字符串转整数
     *
     * @param str
     * @param defValue
     * @return
     */
    public static int toInt(String str, int defValue) {
        try {
            return Integer.parseInt(str);
        } catch (Exception e) {
        }
        return defValue;
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static int toInt(Object obj) {
        if (obj == null)
            return 0;
        return toInt(obj.toString(), 0);
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static long toLong(String obj) {
        try {
            return Long.parseLong(obj);
        } catch (Exception e) {
        }
        return 0;
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static double toDouble(String obj) {
        try {
            return Double.parseDouble(obj);
        } catch (Exception e) {
        }
        return 0.0;
    }

    /**
     * 对象转整数
     *
     * @param obj
     * @return 转换异常返回 0
     */
    public static float toFloat(String obj) {
        try {
            return Float.parseFloat(obj);
        } catch (Exception e) {
        }
        return 0.0f;
    }

    /**
     * 如果含小数位 输出小数位，否则去掉小数位
     *
     * @param price
     * @return
     */
    public static String getPrettyPrice(float price) {
        int intPrice = (int) price;
        if ((price - intPrice) == 0f) {
            return String.valueOf(intPrice);
        }
        return String.valueOf(price);
    }

    public static List<String> stringToList(String str, String seperator) {
        List<String> itemList = new ArrayList<String>();
        if (isEmpty(str)) {
            return itemList;
        }
        StringTokenizer st = new StringTokenizer(str, seperator);
        while (st.hasMoreTokens()) {
            itemList.add(st.nextToken());
        }

        return itemList;
    }

    /**
     * 以一种简单的方式格式化字符串
     * 如  String s = StringHelper.format("{0} is {1}", "apple", "fruit");
     * System.out.println(s);	//输出  apple is fruit.
     *
     * @param pattern
     * @param args
     * @return
     */
    public static String format(String pattern, Object... args) {
        String result = "";
        for (int i = 0; i < args.length; i++) {
            result = pattern.replace("{" + i + "}", String.valueOf(args[i]));
        }
        return result;
    }

    /**
     * 判断是不是一个合法的名字,只能包含汉字和字母
     *
     * @param name
     * @return
     */
    public static boolean isChineseName(Context context, EditText name) {
        if (!TextUtils.isEmpty(name.getText().toString().trim())) {
            if (chineseName.matcher(name.getText().toString()).matches()) {
                return true;
            } else {
                ToastUtils.toastMessage(context, R.string.input_u_correct_name);
                return false;
            }
        } else {
            ToastUtils.toastMessage(context, R.string.empty_name);
            return false;
        }
    }

    /**
     * 判断是否为数字
     *
     * @param txt
     * @return
     */
    public static boolean isFigure(String txt) {
        Pattern p = Pattern.compile("[0-9]*");
        Matcher m = p.matcher(txt);
        return m.matches();
    }

    /**
     * 判断是不是一个合法密码
     *
     * @param context
     * @param psw
     * @return
     */
    public static boolean isPassword(Context context, String psw) {
        if (!TextUtils.isEmpty(psw)) {
            if (password.matcher(psw).matches()) {
                return true;
            } else {
                ToastUtils.toastMessage(context, R.string.input_correct_psw);
                return false;
            }
        } else {
            ToastUtils.toastMessage(context, R.string.empty_psw);
            return false;
        }
    }

    /**
     * 保证String格式为phone
     *
     * @param phone
     * @return
     */
    public static String trimPhone(String phone) {
        String result = "";
        if (isEmpty(phone)) return null;

        result = phone.replaceAll("-", "").replaceAll(" ", "");

        if (result.startsWith("+86"))
            result = phone.substring(3);

        return result.trim();
    }

    /*
     * 去str中的空格
     * @return
     */
    public static String getNoSpaceStr(String str) {
        if (str.contains(" ")) {
            str.replace(" ", "");
        }
        return str;
    }

    /**
     * Url正则匹配
     *
     * @param str
     * @return
     */
    public static Pattern getUrlPattern(String str) {
        Pattern pattern;
        if (str.contains("http")) {
            pattern = Pattern.compile("[http|https]+[://]+[0-9A-Za-z:/[-]_#[?][=][.]]*", Pattern.CASE_INSENSITIVE);
        } else if (str.contains("www")) {
            pattern = Pattern.compile("[www]+[.][0-9A-Za-z:/[-]_#[?][=][.]]*", Pattern.CASE_INSENSITIVE);
        } else {
            pattern = Pattern.compile("([a-zA-Z0-9]([a-zA-Z0-9\\-]{0,61}[a-zA-Z0-9])?\\.)+[a-zA-Z]{2,6}", Pattern.CASE_INSENSITIVE);
        }
        return pattern;
    }

    /**
     * 检测验证码是否正确
     *
     * @return
     */
    public static boolean checkValidCode(Context context, EditText validCode) {
        if (!TextUtils.isEmpty(validCode.getText().toString().trim())) {
            if (validCode.getText().toString().trim().length() == 6) {
                return true;
            } else {
                ToastUtils.toastMessage(context, R.string.input_correct_valid);
                return false;
            }
        } else {
            ToastUtils.toastMessage(context, R.string.empty_valid);
            return false;
        }
    }

    public static boolean checkPhoneNum(Context context, EditText phone) {
        if (!TextUtils.isEmpty(phone.getText().toString().trim())) {
            String phoneNum = phone.getText().toString().trim().replace(" ", "");
            if (isMobile(phoneNum)) {
                return true;
            } else {
                ToastUtils.toastMessage(context, R.string.input_u_correct_phone);
                return false;
            }
        } else {
            ToastUtils.toastMessage(context, R.string.empty_phone);
            return false;
        }
    }


    /**
     * 在url上添加参数
     */
    public static String appendParam(String url, String param, String value) {
        //hotfix for old version
        Pattern p = Pattern.compile(".*token=$");
        Matcher matcher = p.matcher(url);
        if (matcher.matches() && "token".equals(param)) {
            return url + value;
        }

        //normal start here
        StringBuilder result = new StringBuilder(url);
        if (url.contains("?")) result.append("&");
        else result.append("?");
        result.append(param).append("=").append(value);
        LogUtil.d(TAG, result.toString());
        return result.toString();
    }

    /**
     * 检测路径是否为正常的图片路径
     *
     * @param path
     * @return
     */
    public static boolean isNormalImagePath(String path) {
        String extension = path.substring(path.lastIndexOf('.'));
        return extension != null && (extension.equalsIgnoreCase(".jpg") || extension.equalsIgnoreCase(".jpeg") || extension.equalsIgnoreCase(".png"));
    }

    public static boolean isSupportedURL(String url) {
        if (isEmpty(url))
            return false;

        return url.matches("^(http|https|com.xiangirkui.imbxr):[/]{2}.*");
    }

    public static String emptyOrNot(Object object) {
        String str = object == null ? "" : String.valueOf(object);
        return isEmpty(str) ? "" : str;
    }


    /**
     * 去除字符串首尾空格(包括半角，全角的空格)
     *
     * @param source 原字符串
     * @return 去除空格的字符串
     */
    public static String trimSpace(String source) {
        return source == null ? source : source.replaceAll("^[\\s　]*|[\\s　]*$", "");
    }

    /**
     * 获取限制长度后的字符串
     *
     * @param limit
     * @param string
     * @return
     */
    public static String getLimitString(int limit, String string) {
        if (string == null || limit < 1)
            return string;

        StringBuilder sb = new StringBuilder();
        int currentLength = 0;
        for (char c : string.toCharArray()) {
            try {
                currentLength += String.valueOf(c).getBytes("GBK").length;
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                currentLength += 1;
            }

            if (currentLength <= limit) {
                sb.append(c);
            } else {
                break;
            }
        }
        return sb.toString() + (sb.toString().length() < string.length() ? "..." : "");
    }
}
